<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>用户管理</span>
      </div>
      <!-- 搜索表单 -->
      <el-form :model="searchForm" label-width="80px" style="margin-top: 20px;">
        <el-row :gutter="10">
          <el-col :span="6">
            <el-form-item label="名称">
              <el-input v-model="searchForm.nickname" placeholder="请输入昵称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-button type="primary" @click="UserListArray">搜索</el-button>
          </el-col>
          <el-col :span="2">
            <el-button type="primary" @click="clearsearch">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </template>

    <!-- 表格内容 -->
    <el-table :data="userListData" style="width: 100%" v-loading="loading">
      <el-table-column label="序号" width="150" type="index" />
      <el-table-column label="头像" prop="userPic" width="200px">
        <template #default="{ row }">
          <el-image
              style="width: 80px; height: 80px; border-radius: 4px;"
              :src="row.userPic"
              v-if="row.userPic"
              fit="cover"
          >
            <template #error>
              <div class="image-error">
                <el-icon><Picture /></el-icon>
              </div>
            </template>
          </el-image>
          <span v-else>无头像</span>
        </template>
      </el-table-column>

      <el-table-column label="昵称" prop="nickname" />
      <el-table-column label="用户名" prop="username" />
      <el-table-column label="邮箱" prop="email" />
      <el-table-column label="电话" prop="phone" />
<!--      <el-table-column label="操作" width="180">-->
<!--        <template #default="{ row }">-->
<!--          <el-button :icon="Document" circle plain type="info" @click="handleEdit(row)" />-->
<!--        </template>-->
<!--      </el-table-column>-->
      <template #empty>
        <el-empty description="暂无用户数据" />
      </template>

    </el-table>

    <!-- 分页条 -->
    <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[3, 5, 10, 15]"
                   layout="jumper, total, sizes, prev, pager, next" background :total="total" @size-change="onSizeChange"
                   @current-change="onCurrentChange" style="margin-top: 20px; justify-content: flex-end" />


    <router-view></router-view>

  </el-card>
</template>

<script setup>
import { Edit, Delete, Document, Plus, Picture } from '@element-plus/icons-vue'
import { ref, watch } from 'vue'
import {listAllArray, addUserDataInfo, updateUserInfo} from "@/api/user.js";
import { ElMessage, ElMessageBox } from "element-plus";
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import {useTokenStore} from "@/stores/token.js";
import { useRouter } from 'vue-router'
const tokenStore = useTokenStore();
const router = useRouter()

// 用户列表数据模型
const userListData = ref([])
// 标题显示
const titleView = ref('')
// 添加数据模型
const UserModel = ref({
  username:'',
  password:'',
  id: '',
  roleId: '',
  email: '',
  phone: '',
  nickname: '',
  userPic: '',
})
// 添加表单校验规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
  ],
  nickname: [
    { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱', trigger: 'blur' }
  ],
  phone: [
    { min: 1, max: 11, message: '长度在 1 到 11 个字符', trigger: 'blur' }
  ],
  roleId: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
}

// 分页条数据模型
const pageNum = ref(1) // 当前页
const total = ref(0) // 总条数
const pageSize = ref(15) // 每页条数

// 搜索条件数据模型
const searchForm = ref({
  nickname: '',
  roleId: 'ROLE_customer',
})

// 当每页条数发生了变化，调用此函数
const onSizeChange = (size) => {
  pageSize.value = size
  // 重新获取数据
  UserListArray()
}
// 当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
  pageNum.value = num
  // 重新获取数据
  UserListArray()
}
const loading = ref(false);

// 获取用户列表数据
const UserListArray = async () => {
  loading.value = true;
  try {
    const result = await listAllArray({
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      ...searchForm.value // 传递搜索条件
    });
    if (result && result.res) {
      // 校验和处理日期格式
      result.res.forEach(user => {
        user.createTime = handleDate(user.createTime)
        user.updateTime = handleDate(user.updateTime)
      })
      userListData.value = result.res;
      total.value = result.res.length;
    } else {
      console.error('接口返回数据格式不正确，缺少 data 属性');
      ElMessage.error('加载用户列表失败，接口返回数据格式不正确');
    }
  } catch (error) {
    console.error('数据获取失败:', error)
    ElMessage.error('加载用户列表失败')
  }finally {
    loading.value = false; // 结束加载
  }
}

// 处理日期格式
const handleDate = (dateStr) => {
  try {
    const [year, month, day] = dateStr.split('-').map(Number)
    if (isNaN(year) || isNaN(month) || isNaN(day)) {
      return ''
    }
    const newDate = new Date(year, month - 1, day)
    return newDate.toISOString().slice(0, 19).replace('T', ' ')
  } catch (error) {
    return ''
  }
}

const clearsearch=()=>{
  searchForm.value={
    nickname: '',
    roleId: 'ROLE_customer'
  }
  UserListArray()
}


// 清空模型的数据
const clearData = () => {
  UserModel.value = {
    username: '',
    password: '',
    id: '',
    roleId: '',
    email: '',
    phone: '',
    nickname: '',
    userPic: ''
  }
}

// 处理查看操作
const handleEdit = (row) => {
  router.push({
    name: 'housesItemDetailBuy',
    params: { id: row.id },
    // query: { from: 'housesManagement' } // 添加来源标识
  })
}

UserListArray()


</script>

<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .el-tag {
    margin: 2px;
  }
}

/* 抽屉样式 */
.avatar-uploader {
  :deep() {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }

    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }

    .el-upload:hover {
      border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}
.editor {
  width: 100%;
  :deep(.ql-editor) {
    min-height: 200px;
  }
}
</style>
